#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#define Path "."
#define Fifo_name "FIFO"

#define ERR_EXIT(m) \
    do              \
    {               \
        perror(m);  \
        exit(EXIT_FAILURE);\
    } while(0)

class NamePipe
{
public:
    NamePipe(const std::string& path, const std::string& name)
        :_path(path), _name(name)
    {
        _FileName = _path + "/" + _name;
        umask(0);
        int n = mkfifo(_FileName.c_str(),0666);
        if(n < 0)
            ERR_EXIT("mkfifo");
        else
            std::cout << "make fifo success" << std::endl;
    }
    ~NamePipe()
    {
        int n = unlink(_FileName.c_str());
        if(n != 0)
            ERR_EXIT("unlink");
        else
            std::cout << "remove fifo success" << std::endl;
    }
private:
    std::string _path;
    std::string _name;
    std::string _FileName;
};

class FifoManager
{
public:
    FifoManager(const std::string& path, const std::string& name)
        :_name(name), _path(path), _fd(-1)
    {
        _FileName = _path + "/" + _name;
    }
    void OpenForRead()
    {
        _fd = open(_FileName.c_str(),O_RDONLY);
        if(_fd < 0)
            ERR_EXIT("open");
        else
            std::cout << "open success" <<std::endl;
    }
    void Read()
    {
        char buffer[1024];
        while(true)
        {
            int num = read(_fd,buffer,sizeof(buffer)-1);
            if(num > 0)
            {
                buffer[num] = 0;
                std::cout << buffer << std::endl;
            }
            else if (num == 0)
            {
                std::cout << "管道关闭" << std::endl;
                break;
            }
            else
            {
                break;
            }
        }
    }

    void OpenForWrite()
    {
        _fd = open(_FileName.c_str(),O_WRONLY);
        if(_fd < 0)
            ERR_EXIT("open");
        else
            std::cout << "open success" << std::endl;
    }

    void Write()
    {
        std::string message;
        while(true)
        {
            getline(std::cin,message);
            int n = write(_fd,message.c_str(),message.size());
        }
    }
    
    void Close()
    {
        if(_fd > 0)   
            close(_fd);
    }

    ~FifoManager()
    {

    }

private:
    std::string _name;
    std::string _path;
    std::string _FileName;
    int _fd;
};